package org.hackystat.projectbrowser.page;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.PropertyModel;
import org.hackystat.ambientdevice.xml.ConfigurationSaver;
import org.hackystat.projectbrowser.ProjectBrowserApplication;
import org.hackystat.projectbrowser.ProjectBrowserSession;
import org.hackystat.projectbrowser.page.projects.ProjectSelect;
import org.hackystat.sensorbase.resource.projects.jaxb.Project;
import org.hackystat.utilities.tstamp.Tstamp;

/**
 * Provides a base class with associated markup that all ProjectBrowser pages (except for signin)
 * should inherit from. See http://wicket.apache.org/examplemarkupinheritance.html for an
 * explanation of how this works.
 * 
 * @author Philip Johnson
 * @author Sonwright M. Gomez
 */
public class ProjectBrowserBasePage extends WebPage {

  /** Support serialization. */
  private static final long serialVersionUID = 1L;

  /** The project name this user has selected in the ProjectDate form. */
  protected String projectName = "";

  /** The date this user has selected in the ProjectDate form. */
  protected long date = getDateToday().getTime();

  /** The project name this user has selected. */
  private Project project = null;

  /** Displays text at the bottom of the screen for user information. */
  protected String footerFeedback = "";

  /** Checks to make sure that a server already isn't up. */
  private boolean serverIsRunning = true;

  private List<org.hackystat.ambientdevice.server.jaxb.Project> projectTypeXml = 
    new ArrayList<org.hackystat.ambientdevice.server.jaxb.Project>();

  /**
   * Create the ProjectBrowserBasePage.
   */
  public ProjectBrowserBasePage() {
    ProjectBrowserApplication app = (ProjectBrowserApplication) getApplication();
    add(HeaderContributor.forCss(org.hackystat.projectbrowser.Start.class,
        "style/boilerplate/screen.css", "screen"));
    add(HeaderContributor.forCss(org.hackystat.projectbrowser.Start.class,
        "style/boilerplate/print.css", "print"));
    add(new Label("title", app.getApplicationName()));
    add(new Label("application-name", (app.hasApplicationLogo() ? "" : app.getApplicationName())));
    // Provide a default value for the projectName field.
    List<String> projectNames = ProjectBrowserSession.get().getProjectNames();
    if ((projectNames != null) && !projectNames.isEmpty()) {
      this.projectName = projectNames.get(0);
    }
    // Gets a list of the projectTypeXml
    this.projectTypeXml = ProjectBrowserSession.get().getProjectsFromXML();

    add(new BookmarkablePageLink("projectSelect", ProjectSelect.class));
    add(new Link("LogoutLink") {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      /** Go to the home page after invalidating the session. */
      @Override
      public void onClick() {
        getSession().invalidate();
        setResponsePage(getApplication().getHomePage());
      }
    });
    add(new Link("SaveConfiguration") {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      /** Go to the home page after invalidating the session. */
      @Override
      public void onClick() {
        if (saveConfiguration()) {
          ProjectBrowserSession.get().stopServer();
          serverIsRunning = false;
          ProjectBrowserSession.get().startServer();
          serverIsRunning = true;
          setFooterFeedback("Ambient Server Restarted");
          setFooterFeedback("Save Successful, Server also restarted to apply changes.");
        }
        else {
          setFooterFeedback("There was an error with the save.  Nothing was saved");
        }

      }
    });
    /*
     * add(new Link("StartServer") {
     *//** Support serialization. */
    /*
     * private static final long serialVersionUID = 1L;
     *//** Go to the home page after invalidating the session. */
    /*
     * @Override public void onClick() { if (!serverIsRunning) {
     * ProjectBrowserSession.get().startServer(); serverIsRunning = true; setFooterFeedback("Ambient
     * Server Started"); } else { ProjectBrowserSession.get().stopServer(); serverIsRunning = false;
     * ProjectBrowserSession.get().startServer(); serverIsRunning = true; setFooterFeedback("Ambient
     * Server Restarted"); }
     *  } }); add(new Link("StopServer") {
     *//** Support serialization. */
    /*
     * private static final long serialVersionUID = 1L;
     *//** Go to the home page after invalidating the session. */
    /*
     * @Override public void onClick() { ProjectBrowserSession.get().stopServer(); serverIsRunning =
     * false; setFooterFeedback("Ambient Server Stopped"); } });
     */
    add(new Label("FooterFeedback", new PropertyModel(this, "footerFeedback")));
    add(new Label("UserEmail", new PropertyModel(ProjectBrowserSession.get(), "userEmail")));
  }

  /**
   * The action to be performed when the user has set the Project and Date fields.
   */
  public void onProjectDateSubmit() {
    // do nothing in default case.
  }

  /**
   * make a Date that represent today, at 0:00:00.
   * 
   * @return the Date object.
   */
  public static final Date getDateToday() {
    XMLGregorianCalendar time = Tstamp.makeTimestamp();
    time.setTime(0, 0, 0);
    return time.toGregorianCalendar().getTime();
  }

  /**
   * The getter for the footer feedback.
   * @param project the project to set
   */
  public void setProject(Project project) {
    this.project = project;
  }
/**
 * The setter for the footer feedback.
 * @param string the string to set.
 */
  public void setFooterFeedback(String string) {
    this.footerFeedback = string;
  }

  /**
   * The getter for the project.
   * @return the project
   */
  public Project getProject() {
    return project;
  }

  /**
   * The setter for the date.
   * @param date the date to set
   */
  public void setDate(Date date) {
    this.date = date.getTime();
  }

  /**
   * The getter for the date.
   * @return the date
   */
  public Date getDate() {
    return new Date();
  }
  
  /**
   * The method to save the configuration. 
   * @return return true if configuration is saved. 
   */
  public boolean saveConfiguration() {
    try {
      ConfigurationSaver cs = new ConfigurationSaver();
      cs.saveConfigurationXml(ProjectBrowserSession.get().getConfiguration());
      return true;
    }
    catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return false;
    }

  }
  
}
